package io.wit.modules.gen.controller;

import io.wit.common.utils.PageUtils;
import io.wit.common.utils.Query;
import io.wit.common.utils.R;
import io.wit.common.xss.XssHttpServletRequestWrapper;
import io.wit.modules.gen.service.SysGeneratorService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 代码生成器
 * @author chenshun
 */
@Controller
@RequestMapping("/sys/generator")
public class SysGeneratorController{

    @Autowired
    private SysGeneratorService sysGeneratorService;

    /**
     * 列表
    */
    @ResponseBody
    @RequestMapping("/list")
    @RequiresPermissions("sys:generator:list")
    public R list(@RequestParam Map<String,Object> params){
        //查询列表数据
        final Query query = new Query(params);
        final List<Map<String,Object>> list = sysGeneratorService.queryList(query);
        final int total = sysGeneratorService.queryTotal(query);
        final PageUtils pageUtil = new PageUtils(list,total,query.getLimit(),query.getPage());
        return R.ok().put("page",pageUtil);
    }

    /**
     * 生成代码
    */
    @RequestMapping("/code")
    @RequiresPermissions("sys:generator:code")
    public void code(final HttpServletRequest request,final HttpServletResponse response) throws IOException{
        //获取表名，不进行xss过滤
        final HttpServletRequest orgRequest = XssHttpServletRequestWrapper.getOrgRequest(request);
        final String tables = orgRequest.getParameter("tables");
        final byte[] data = sysGeneratorService.generatorCode(new String[]{tables});
        response.reset();
        response.setHeader("Content-Disposition","attachment; filename="+tables+"\".zip\"");
        response.addHeader("Content-Length","" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data,response.getOutputStream());
    }
}